<!--
 * @Author: yl
 * @Date: 2024-04-09 16:07:23
 * @LastEditTime: 2024-05-06 16:13:14
 * @LastEditors: Please set LastEditors
 * @Description: 养殖品种页面
-->
<template>
  <BaseMainSlot :show-tab="true" :show-search-box="false">
    <template v-slot:btn-box>
      <ActionBar
        :page-no="614"
        :add-active="addActive"
        :del-active="delActive"
        :edit-active="editActive"
        :has-edit="false"
        :hasSave="false"
        @add="add"
        @edit="edit"
        @del="del"
      />
    </template>
    <template v-slot:search-box>
      <SearchBox @search="search">
        <div class="common-search-item">
          <div class="label"></div>
          <div class="input"></div>
        </div>
      </SearchBox>
    </template>
    <template v-slot:table-box>
      <ZnFilterTable
        :loadings="loading"
        :list-data="tableData"
        :prop-list="tableDataList"
        scope-no="breedVarietyNo"
        @handleSelectionChange="handleSelectionChange"
        @rowClick="handleEdit"
        @tableUpdate="tableUpdate"
      >
        <template v-slot:description="{ row }">
          <span>{{ row.description?row.description:'——' }}</span>
        </template>
        <template v-slot:url="{ row }">
          <el-button
            class="text-btn-cursor"
            type="text"
            size="small"
            @click="previewImg(row)"
          >点击查看</el-button>
        </template>
        <template v-slot:operation="{ row }">
          <el-button
            v-if="judgePermission(614, 'edit')"
            class="text-btn-cursor"
            type="text"
            size="small"
            @click="edit"
          >
            <i class="el-icon-edit-outline"></i> 修改
          </el-button>
          <el-button
            v-else-if="!judgePermission(614, 'edit')"
            disabled
            class="text-btn-cursor"
            type="text"
            size="small"
          >
            <i class="el-icon-edit-outline"></i> 修改
          </el-button>
          <el-button
            v-if="judgePermission(614, 'delete')"
            class="text-btn-cursor cursor-delete"
            type="text"
            size="small"
            @click="handleDelete(row.breedVarietyNo)"
          >
            <i class="el-icon-delete"></i> 删除
          </el-button>
          <el-button
            v-else-if="!judgePermission(614, 'delete')"
            disabled
            class="text-btn-cursor cursor-delete"
            type="text"
            size="small"
          >
            <i class="el-icon-delete"></i> 删除
          </el-button>
        </template>
      </ZnFilterTable>
      <Pagination
        :page-size="pageSize"
        :current-page="currentPage"
        :total-size="totalSize"
        @changePageSize="changePageSize"
        @changeCurrentPage="changeCurrentPage"
      />
    </template>
    <template v-slot:dialog>
      <el-dialog
        :title="titleText + '养殖品种信息'"
        :visible.sync="dialogFormVisible"
        @close="cancel('formData')"
      >
        <el-form
          ref="formData"
          label-position="left"
          :model="formData"
          :rules="rules"
          class="el-form"
        >
          <el-form-item
            v-for="item,index in formDataList"
            :key="index"
            :label="item.name + ':'"
            :prop="item.porp"
            class="w50p"
          >
            <el-input
              v-if="item.type === 'input'&&item.inputType !== 'number'"
              v-model="formData[ `${item.porp}`]"
              :placeholder="'请输入' + item.name"
              clearable
            />
            <el-input-number
              v-if="item.type === 'input'&&item.inputType === 'number'"
              v-model.number="formData[ `${item.porp}`]"
              :type="item.inputType"
              :placeholder="'请输入' + item.name"
              clearable
              controls-position="right"
              :min="0"
            />
            <el-select
              v-if="item.type === 'Select'"
              v-model="formData[ `${item.porp}`]"
              filterable
              :placeholder="'请选择' + item.name"
              clearable
              disabled
              @change="SelectLinkage($event, item.linkage, index - 1)"
            >
              <el-option
                v-for="items,indexs in item.typeObj.list"
                :key="indexs"
                :label="items[item.typeObj.listName[0]]"
                :value="items[item.typeObj.listName[1]]"
              />
              <!-- <el-option label="女" value="女" /> -->
              <!-- <el-option label="无" value="无" /> -->
            </el-select>
            <el-date-picker
              v-if="item.type === 'TimePicker'"
              v-model="formData[ `${item.porp}`]"
              type="date"
              value-format="yyyy-MM-dd"
              :placeholder="'选择' + item.name"
            />
            <el-input
              v-if="item.type === 'textarea'"
              type="textarea"
              class="w100p"
              autosize
              v-model="formData[ `${item.porp}`]"
              :placeholder="'请输入' + item.name"
              clearable
            />
            <UploadPics
              v-if="item.type === 'img'"
              ref="UploadPics"
              v-model="uploadPictureList"
              :limit="1"
              accept=".jpg, .jpeg, .png"
              @input="handlerAddFileList($event, 'png')"
              @delectFileId="handlerDeleteId($event, 'png')"
            />
          </el-form-item>
        </el-form>
        <div v-if="nowChanceStau !== ''" slot="footer" class="dialog-footer">
          <el-button class="zh-button-one" @click="cancel('formData')">取 消</el-button>
          <el-button
            class="zh-button-two"
            type="primary"
            @click="save('formData')"
          >保 存</el-button>
        </div>
      </el-dialog>
      <el-dialog title="查看图片" :visible.sync="dialogImgVisible">
        <el-image
          style="max-width: 100px; height: 100px"
          :src="imgObj.url"
          :preview-src-list="[imgObj.url]"
        >
          <div slot="error" class="image-slot">
            <i class="el-icon-picture-outline"></i>
          </div>
        </el-image>
      </el-dialog>
    </template>
  </BaseMainSlot>
</template>

<script>
import ActionBar from "@/components/ActionBar";
import Pagination from "@/components/Pagination";
import basicInfoManage from "@/api/trace-source-web/base-infor-manage/breed-varieties-management.js";
import SearchBox from "@/components/SearchBox";
import BaseMainSlot from "@/components/BaseMainSlot/newBaseMainSlot";
import { mymixin } from "@/utils/mixins";
import TypePopover from "@/components/ZnFilterTable/typePopover.vue";
import { mapGetters } from "vuex";

import basicType from "@/api/basic-info-manage/agricultural-type-manage/index.js";
import UploadPics from "@/components/UploadPics/upload-img-list.vue";
export default {
  name: "SheepInformation",
  components: {
    ActionBar,
    Pagination,
    BaseMainSlot,
    SearchBox,
    TypePopover,
    UploadPics,
  },
  mixins: [mymixin],
  data () {
    return {
      obj: {
        name: "",
      },
      breedTypeName: "",
      // 员工姓名
      breedTypeNo: "",
      // 选中的数据项数组 employeeId组成 (此数组最多为一个)
      selectedStaffList: [],
      departmentList: [],
      stationList: [],
      // 存储一份
      stationLists: [],
      postName: "",
      postId: "",
      files: {},
      upLoading: false,
      downLoading: false,
      formData: {
        person: {},
      },
      facilityList: [],
      facilityLists: [],
      tableDataList: [
        {
          type: "input", // input Select Checkbox TimePicker
          porp: "breedVarietyName",
          typeObj: {},
          name: "品种名称",
          required: true,
        },
        {
          type: "input", // input Select Checkbox TimePicker
          porp: "cycle",
          typeObj: {},
          name: "品种周期（天）",
          required: true,
          // rules:
        },
        {
          type: "img", // input Select Checkbox TimePicker
          porp: "url",
          slotName: "url",
          typeObj: {},
          name: "品种图片",
          required: false,
          notSearch: true,
        },
        {
          type: "textarea", // input Select Checkbox TimePicker
          porp: "description",
          slotName: "description",
          typeObj: {},
          name: "描述",
          required: false,
          notSearch: true,
        },

        {
          porp: "operation",
          name: "操作",
          slotName: "operation",
          fixed: true,
          minWidth: "160",
          typeObj: {},
          show: false,
          notSearch: true,
        },
      ],
      formDataList: [
        {
          type: "Select", // input Select Checkbox TimePicker
          porp: "breedTypeNo",
          typeObj: {},
          name: "养殖类别",
          required: true,
        },
        {
          type: "input", // input Select Checkbox TimePicker
          porp: "breedVarietyName",
          typeObj: {},
          name: "品种名称",
          required: true,
        },
        {
          type: "input", // input Select Checkbox TimePicker
          porp: "cycle",
          inputType: "number",
          typeObj: {},
          name: "品种周期（天）",
          required: true,
          // rules:
        },
        {
          type: "textarea", // input Select Checkbox TimePicker
          porp: "description",
          typeObj: {},
          name: "描述",
          required: false,
        },
        {
          type: "img", // input Select Checkbox TimePicker
          porp: "url",
          typeObj: {},
          name: "品种图片",
          required: false,
        },
      ],
      rules: {
        breedVarietyName: [
          {
            required: true,
            message: "品种名称不能为空",
            trigger: ["blur", "change"],
          },
        ],

        cycle: [
          {
            required: true,
            message: "品种周期不能为空",
            trigger: "blur",
          },
        ],
      },
      topitemtypestu: true,
      searchObj: {},
      //图片
      imgObj: {},
      uploadPictureList: [],
      dialogImgVisible: false,
    };
  },
  computed: {
    ...mapGetters({
      judgePermission: "permission/judgePermission",
    }),
  },
  created() {
    this.breedTypeName = sessionStorage.breedTypeName;
    if (['dt', 'dp'].includes(sessionStorage.farmingTypeNo)) {
      this.formDataList.shift()
    } else {
      this.getList();
    }
    // this.departmentPost();
  },
  mounted() {
    // 查询部门
    // 获取表格数据
    this.search();
  },
  methods: {
    filterHandler(value, row, column) {
      const property = column["property"];
      return row[property] === value;
    },
    // topitemtype(e) {
    //   this.topitemtypestu = e;
    //   this.getTableDataList();
    // },
    async getList() {
      const { data: res } = await basicType.queryByCondition({});
      this.$set(this.formDataList[0], "typeObj", {
        list: res,
        listName: ["breedTypeName", "breedTypeNo"],
      });
    },
    previewImg(row) {
      this.imgObj = row;
      this.dialogImgVisible = true;
    },
    // 添加-品种图片
    handlerAddFileList(data, type) {
      if (type === "png") {
        this.uploadPictureList = data.list;
      }
    },

    // 删除-轮播图/视频
    handlerDeleteId(file, type) {
      // this.$confirm()
      this.$confirm(
        `确认删除该${
          type === "png" ? "图片" : type === "video" ? "视频" : "文件"
        }`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
          customClass: "myClass",
        }
      )
        .then(() => {
          // console.log(file)
          if (type === "png") {
            let fileId = file.url;
            this.uploadPictureList.splice(
              this.uploadPictureList.findIndex((i) => i.url == fileId),
              1
            );
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    async SelectLinkage(e, x) {
      if (x) {
        this.$set(this.formData, "columnNo", undefined);
        // console.log(this.formDataList, this.facilityLists);
      }
    },
    getTableDataList() {
      this.loading = true;
      let params = {
        page: this.currentPage,
        size: this.pageSize,
        entity: { ...this.searchObj },
      };
      basicInfoManage.getList(params).then((res) => {
        this.loading = false;
        let data = res.data;
        // 赋值总条数
        if (data) {
          this.totalSize = data.totalElements;
          // 赋值数组
          this.tableData = JSON.parse(
            this.livestock(JSON.stringify(data.content))
          );
          // console.log(this.tableData)
          this.addblankmet();
          this.resetActionBar();
        }
      });
    },

    search() {
      this.currentPage = 1;
      this.getTableDataList();
    },
    changePageSize(pageSize) {
      this.pageSize = pageSize;
      this.getTableDataList();
    },
    changeCurrentPage(currentPage) {
      this.currentPage = currentPage;
      this.getTableDataList();
    },
    handleEdit(row) {
      this.uploadPictureList = [];
      // TODO 点击行元素后 edit
      this.formData = JSON.parse(JSON.stringify({ ...row, ...row.person }));
      if (this.formData.url) {
        if (this.uploadPictureList.length === 0) {
          this.uploadPictureList.push({ url: this.formData.url });
        } else {
          // this.uploadPictureList[0] = { url: this.formData.url };
          this.$set(this.uploadPictureList, 0, { url: this.formData.url })
        }
      }
      this.editActive = true;
    },
    handleSelectionChange(list) {
      this.selectedStaffList = [];
      this.selectedStaffList = list.map((item) => item.breedVarietyNo);
      if (this.selectedStaffList.length > 0) this.delActive = true;
      else this.delActive = false;
      // 多个处理为单个数据
      // if (this.selectedStaffList.length > 1) {
      //   this.$message.warning("员工不可多选删除！");
      //   return;
      // } else {
      //   this.selectedStaffList.splice(0, this.selectedStaffList.length - 1);
      // }
    },
    delmessage() {
      // if (this.selectedStaffList.length > 1) {
      //   // this.$message.warning("员工不可多选删除！");
      //   return;
      // } else {
      basicInfoManage.delList(this.selectedStaffList).then((res) => {
        if (res.code === 1) {
          this.$message.success(res.msg);
          this.search();
        } else {
          this.$message.warning(res.msg || "删除失败");
        }
      });
      // this.selectedStaffList.splice(0, this.selectedStaffList.length - 1);
      // }
    },
    handleDelete(val) {
      this.$confirm("此操作将永久删除该条数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        customClass: "myClass",
      })
        .then(() => {
          basicInfoManage.del(val).then((res) => {
            if (res.code === 1) {
              this.$message.success(res.msg);
              this.search();
            } else {
              this.$message.warning(res.msg || "删除失败");
            }
          });
        })
        .catch(() => {
          // this.$message({
          //   type: "info",
          //   message: "已取消删除"
          // });
        });
    },
    addPlus() {
      this.uploadPictureList = [];
      this.$set(this.formData, "breedTypeNo", sessionStorage.breedTypeNo);
    },
    save(formData) {
      console.log(this.formData);
      this.$refs[formData].validate((valid) => {
        if (valid) {
          this.formData.farmingTypeNo = sessionStorage.farmingTypeNo;
          if (this.uploadPictureList.length > 0) {
            this.formData.url = this.uploadPictureList[0].url;
          }
          if (this.nowChanceStau === "edit") {
            // 编辑接口
            // 巡检点数组赋值进formData
            let formData = { ...this.formData };
            basicInfoManage.edit(formData).then((res) => {
              if (res.code === 1) {
                this.$message.success(res.msg || "修改成功！");
                this.cancel("formData");
                // this.postId = "";
                this.search();
              } else {
                this.$message.error(res.msg || "修改失败！");
              }
            });
          } else if (this.nowChanceStau === "add") {
            // 新增接口
            this.formData.organizationNo = sessionStorage.organizationNo;
            // this.formData.postId = this.postId;
            // this.formData.postName = this.postName;
            let formData = {};
            let person = { ...this.formData };
            formData = person;

            basicInfoManage.add(formData).then((res) => {
              if (res.code === 1) {
                this.$message.success(res.msg || "新增成功！");
                this.cancel("formData");
                // this.postId = "";
                this.search();
              } else {
                this.$message.error(res.msg || "新增失败！");
              }
            });
          }
        } else {
          return false;
        }
      });
    },
  },
};
</script>

<style scoped lang="scss">
@import "~@/styles/variables.scss";
::v-deep .el-form-item__content {
  align-items: flex-start !important;
}
// .staff-manage {
//   width: 100%;
//   height: 100%;
::v-deep .el-form-item__content {
  // display: flex;
  justify-content: space-between;
}
::v-deep .el-form-item__label {
  // min-width: 100px !important;
  text-align: end;
}
// }
// }
.DownExcel {
  margin-left: 20px;
  // background-color: #03bfef;
  // // border: 1px solid ;
}
::v-deep .pull-right {
  // height: 28px;
  // margin-left: 10px;
  .upload-demo {
    height: 100%;
    .el-upload {
      height: 100%;
      .el-button {
        height: 100%;
      }
    }
  }
}
::v-deep .el-form-item {
  height: fit-content;
}
</style>
